//
//  UniAudio.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/6/17.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation
import AVFoundation

class UniAudio: NSObject {
    static let shared = UniAudio()
    
    var outputFile: AVAudioFile? = nil
    lazy var audioEngine: AVAudioEngine = {
        let audio = AVAudioEngine()
        return audio
    }()
    
    func configureAudio() {
        let input = audioEngine.inputNode
        let output = audioEngine.outputNode
        //let mixerNode = audioEngine.mainMixerNode

        let bus = 0
        let inputFormat = input.inputFormat(forBus: bus)
        let outputURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!.appendingPathComponent("out.caf")
        print("writing to \(outputURL)")
        
        outputFile = try! AVAudioFile(forWriting: outputURL, settings: inputFormat.settings, commonFormat: inputFormat.commonFormat, interleaved: inputFormat.isInterleaved)

        input.installTap(onBus: bus, bufferSize: 512, format: inputFormat) { (buffer, time) in
            try! self.outputFile?.write(from: buffer)
        }
        
        self.audioEngine.connect(input, to: output, format: nil)
        
        try! audioEngine.start()
        
        
        
        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            print("Finish")
            self.audioEngine.stop()
            self.outputFile = nil
        }
    }
}
